import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_application_cyber/model/cn_net_response.dart';
import 'package:flutter_application_cyber/net/cn_net_helper.dart';
import 'package:flutter_application_cyber/pages/Mine/Models/cn_BlockListModel.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_util_code/toast_utils.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';
import 'package:flutter_application_cyber/tools/cn_common_global.dart';
import 'cn_conversation_list_item.dart';
import '../../tools/cn_event_bus.dart';
import 'dart:async';
import '../../tools/cn_style.dart';
import '../../tools/cn_widget_util.dart';
import 'left_slide_actions.dart';
import 'dart:math';
class CnMessageListPage extends StatefulWidget {
  const CnMessageListPage({super.key});
  @override
  State<CnMessageListPage> createState() => _CnMessageListPage();
}

class _CnMessageListPage extends State<CnMessageListPage>
    implements CnConversationListItemDelegate {
  List blockList = [];
  RCIMIWEngine? _engine;
  int timestamp = DateTime.now().millisecondsSinceEpoch;
  List<RCIMIWConversationType> conversationTypes = [
    RCIMIWConversationType.private,
    RCIMIWConversationType.system
  ];
  List conList = [];
  final Map<String, VoidCallback> _mapForHideActions = {};
// 创建一个Key，用于强制重建Widget
  final GlobalKey _key = GlobalKey();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: RefreshIndicator(
        onRefresh: _onRefresh,
        child: _buildConversationListView(),
      ),
    );
  }

  Widget _buildConversationListView() {
      final Random random = Random();

    return ListView.builder(
      key: _key,
      scrollDirection: Axis.vertical,
      itemCount: conList.length,
      itemBuilder: (BuildContext context, int index) {
        return LeftSlideActions(
          key: ValueKey('${Random().nextInt(10000)}'),
          actionsWidth: 160,
          deleteActionsWillShow: () {
            _deleteConversation(conList[index]);
            conList.removeAt(index);
            setState(() {
              conList = conList;
            });
          },
          topShowActionsWillShow: () {
            // 省略: 弹出是否删除的确认对话框。
            bool isTop = true;
            if (conList[index].top!) {
              isTop = false;
            }
            _setConversationToTop(conList[index], isTop);
          },
          child: CnConversationListItem(this, conList[index]),
          decoration: const BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(5)),
          ),
          actionsWillShow: () {},
          exportHideActions: (hideActions) {},
        );
      },
    );
  }

  /// 下拉刷新回调方法
  Future<Null> _onRefresh() async {
    /// 强制休眠 1 秒
    // await Future.delayed(Duration(seconds: 1));
    /// 更新状态
    updateConversationList();
    _key.currentState?.setState(() {});

    return null;
  }

  @override
  void initState() {
    super.initState();
    _engine = CnGlobal.engine;
    updateConversationList();

    CnEventBus.instance!.addListener(EventKeys.ConversationPageDispose, (arg) {
          // updateConversationList();

      Timer(Duration(milliseconds: 1), () {
        updateConversationList();
      });
    });
  }

  void updateConversationList() async {
    DateTime now = DateTime.now();
    timestamp = now.millisecondsSinceEpoch;
    List<RCIMIWConversationType> conversationTypes = [
      RCIMIWConversationType.private,
      RCIMIWConversationType.system
    ];

    //获取消息
    IRCIMIWGetConversationsCallback? callback = IRCIMIWGetConversationsCallback(
        onSuccess: (List<RCIMIWConversation>? t) {
      conList.clear();
      if (t!.isNotEmpty) {

        setState(() {
        conList.addAll(t);
        });
      } else {
        setState(() {
          conList = [];
        });
      }

    }, onError: (int? code) {
      print(code);
    });

    _engine!.getConversations(conversationTypes, '', timestamp, 50,
        callback: callback);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    CnEventBus.instance!.removeListener(EventKeys.ConversationPageDispose);
  }

  @override
  void didLongPressConversation(
      RCIMIWConversation? conversation, Offset? tapPos) {
    // TODO: implement didLongPressConversation
    // Map<String, String> actionMap = {
    //   RCLongPressAction.DeleteConversationKey:
    //       RCLongPressAction.DeleteConversationValue,
    //   // RCLongPressAction.ClearUnreadKey: RCLongPressAction.ClearUnreadValue,
    //   RCLongPressAction.SetConversationToTopKey: conversation!.top!
    //       ? RCLongPressAction.CancelConversationToTopValue
    //       : RCLongPressAction.SetConversationToTopValue
    // };
    // CnWidgetUtil.showLongPressMenu(context, tapPos!, actionMap, (String? key) {
    //   if (key == RCLongPressAction.DeleteConversationKey) {
    //     _deleteConversation(conversation);
    //   } else if (key == RCLongPressAction.SetConversationToTopKey) {
    //     bool isTop = true;
    //     if (conversation.top!) {
    //       isTop = false;
    //     }
    //     _setConversationToTop(conversation, isTop);
    //   }
    // });
  }

  void _setConversationToTop(RCIMIWConversation conversation, bool isTop) {
    IRCIMIWChangeConversationTopStatusCallback? callback =
        IRCIMIWChangeConversationTopStatusCallback(
            onConversationTopStatusChanged: (int? code) {
//...
      if (code == 0) {
        updateConversationList();
      }
    });

    _engine?.changeConversationTopStatus(
        conversation.conversationType!, conversation.targetId!, null, isTop,
        callback: callback);
  }

  void _deleteConversation(RCIMIWConversation conversation) {
    //删除会话需要刷新会话列表数据

    IRCIMIWRemoveConversationCallback? callback =
        IRCIMIWRemoveConversationCallback(onConversationRemoved: (int? code) {
//...
      if (code == 0) {
        updateConversationList();
      }
    });

    _engine?.removeConversation(
        conversation.conversationType!, conversation.targetId!, null,
        callback: callback);
  }

  @override
  void didTapConversation(RCIMIWConversation? conversation) {
    Map arg = {
      "coversationType": conversation!.conversationType,
      "targetId": conversation.targetId,
      'nickName': '',
    };
    Navigator.pushNamed(context, "/conversation", arguments: arg);
  }
}
